package cn.fql.system.controller;


import cn.fql.basic.util.AjaxResult;
import cn.fql.basic.util.PageList;
import cn.fql.system.domain.Detail;
import cn.fql.system.domain.Type;
import cn.fql.system.query.TypeQuery;
import cn.fql.system.service.IDetailService;
import cn.fql.system.service.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/type")
public class TypeController {

    @Autowired
    private IDetailService iDetailService;
    @Autowired
    private ITypeService typeService;
     /**
     Get http://localhost/type/1
     */
    @GetMapping("/{id}")
    //@PathVariable("id") Long id - 从路径上去获取变量 id 赋值给 Long id
    public Type  findById(@PathVariable("id") Long id){
        return typeService.findById(id);
    }

    /**接口
     查询所有:
     //Get http://localhost/type
     */
    @GetMapping
    public List<Type> findAll(){
        return typeService.findAll();
    }

    /**
     * 接口：分页查询
     * @param typeQuery
     * @return
     */
    //post http://localhost/type 对象
    //返回值要用PageList中的参数总数量 不然无法计算分页数量
    @PostMapping
    public PageList<Type> queryPage(@RequestBody TypeQuery typeQuery){
        return typeService.queryPage(typeQuery);
    }


    /**
     * 删除接口
     * @param id
     * @return
     */
    //delete http://localhost/type/1
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id")Long id){
        try {
            typeService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    /**
     * 添加和修改接口
     * @param type
     * @return
     */
    //put http://localhost/type {对象}
    //RequestBody  请求体:赋值数据 因为不是get请求 无法从地址栏获取数据
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Type type){
        try {
            if(type.getId() == null){
                typeService.save(type);
            }else{
                typeService.update(type);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    /**
     * 批量删除接口
     * @param
     * @return
     */
    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids){
        try {
            typeService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }
    @GetMapping("/type/{id}")
    public List<Detail> loadByTypeId(@PathVariable("id") Long id){
        List<Detail> list = iDetailService.loadByTypeId(id);
        return list;
    }

}
